import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.*;
import java.security.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;


public class Sazana extends JFrame {
	// Sazana - We know each other
	private static final long serialVersionUID = 1L;
	JTextField message;
	JPanel Hpanel;
	JTextArea chat;
	World world;

	// Netzwerk
	Socket echoSocket = null;
	PrintWriter out = null;
//	BufferedReader in = null;
	InputStream in= null;
	ClientThread th = null;

	public static void main(String[] args) {
		new Sazana();
	}
	
	
	//Verbindet zu einem Socket-Server
	public boolean connect(String host) {
		// Netzwerk verbinden
		try {
			echoSocket = new Socket(host, 3333);
			out = new PrintWriter(echoSocket.getOutputStream(), true);
			//	in = new InputStreamReader(echoSocket.getInputStream());
			in= echoSocket.getInputStream();
			th = new ClientThread(in, this);
			th.start();
			out.println("connect#username=" + "UserA" + "#password=" + MakeMD5("abcdefgh"));
			out.println("getguys");
			
			return true;
		} catch (UnknownHostException e) {
			Fehler("Zielhost " + host + " nicht erreichbar.");
			return false;
		} catch (IOException e) {
			Fehler("Kann keine Verbindung mit " + host
					+ " herstellen.");
			
			return false;
		}				
	}
	
	public void disconnect()
	{
	
//		try
//		{
			
			out.println("disconnect#username=" + "UserA" );
//			out.close();
//			in.close();
//			echoSocket.close();
		
//		catch (IOException e) {
//			Fehler("Disconnect.");
//		}				
	}
	
	//Konvertiert einen Text in MD5-Format
	public String MakeMD5(String text)
	{
		try
		{
			byte[] bytesOfMessage = text.getBytes();
		
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] thedigest = md.digest(bytesOfMessage);
			
			return thedigest.toString();
		}
		catch (NoSuchAlgorithmException e){ 
			return "Fehler";
		}
	}
	
	public void Fehler(String ErrCode)
	{
		
		th = null;
		echoSocket = null;		
	}
	
	public Sazana() {
		// Constructor
		super("Sazana");
		
		//Welt muss vor Connect erstellt werden 
		//--> Bei Connect wird schon Guy erzeugt
		world = new World(this);
		//172.16.70.76
		if (connect("localhost")) 
		{			
			setBounds(100, 100, 100, 100);
			
			world.setFocusable(true);
			add(world,BorderLayout.CENTER);
			chat = new JTextArea(5,1);
			chat.setEditable(false);
			chat.setOpaque(false);
			chat.setEditable(false);
			
			//transparent chatArea			
			Hpanel = new JPanel(new GridBagLayout());
				
			message = new JTextField(20);
			JButton senden =new JButton("Senden");
			//design Textfield
			GridBagConstraints c = new GridBagConstraints();
			c.fill=GridBagConstraints.HORIZONTAL;
			c.insets = new Insets(2,2,2,2);  
			c.gridy = 0;
			c.gridx = 0;
			c.gridwidth = 2;
			//Hpanel.add(chat,c);
			Hpanel.add(new JScrollPane(chat),c);
			c.gridwidth = 1;
			c.gridx = 0;
			c.gridy = 1;
			c.weightx = 10.0;
			Hpanel.add(message,c); 
			// design send button
			c.gridx = 1;
			c.gridy = 1;
			c.weightx = 0.0;
			Hpanel.add(senden,c);
			
			add(Hpanel,BorderLayout.SOUTH);
			world.setFocusable(true);
			world.setEnabled(true);
			
			message.addKeyListener(new KeyAdapter(){
				public void keyPressed(KeyEvent e){
					if(e.getKeyCode() == KeyEvent.VK_ENTER) {
						send(message.getText());
						world.requestFocusInWindow();
					}
				}
			});
			addWindowListener(new WindowAdapter() {
				public void windowClosing(WindowEvent e) {
					disconnect();
					System.exit(0);
				}
			});
			senden.addActionListener(new ActionListener() 
	        { 
	            public void actionPerformed(ActionEvent ae) 
	            { 
	            	send(message.getText());
	            }
	        });
			
			pack();
			setVisible(true);
		} else {
			JOptionPane.showMessageDialog(null, "Test", "Test Titel", JOptionPane.OK_OPTION);
			world = null;
		}
		
	}
	
	private void send(String messageChat)
	{
		messageChat = messageChat.trim();
		if (!messageChat.equals("")) {
			out.println("say#" + messageChat);
		}
		message.setText("");
	}

}
